package com.jinzhi.jinzhidata.controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinzhi.jinzhidata.dataobject.User;
import com.jinzhi.jinzhidata.pojo.WX.message.NewsMessage;
import com.jinzhi.jinzhidata.service.SceneService;
import com.jinzhi.jinzhidata.service.UserService;
import com.jinzhi.jinzhidata.util.Constant;
import com.jinzhi.jinzhidata.util.JwtUtil;
import com.jinzhi.jinzhidata.util.WeChatMessageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author vansl
 * @description 用于接收公众号的消息、事件
 * @date 2020-01-09 19:40
 **/
@RequestMapping("/weChat")
@RestController
public class WeChatController {

    @Autowired
    UserService userService;

    @Autowired
    SceneService sceneService;

    @GetMapping
    public String verify(String signature, String timestamp, String nonce, String echostr) {
        if (WeChatMessageUtil.checkSignature(signature, timestamp, nonce)) {
            return echostr;
        }
        return null;
    }

    @PostMapping
    public String onMessageRecived(HttpServletRequest request) {
        // xml格式的消息数据
        String respXml = null;
        // 默认返回的文本消息内容
        String respContent;
        try {
            // 调用parseXml方法解析请求消息
            Map<String, String> requestMap = WeChatMessageUtil.parseXml(request);
            System.out.println(requestMap);
            // 消息类型
            String msgType = requestMap.get(Constant.MsgType);
            String openid = requestMap.get(Constant.FromUserName);
            if (msgType.equals(Constant.REQ_MESSAGE_TYPE_TEXT)) {
                // 文本消息
                String msg = requestMap.get(Constant.Content);
                if (msg.contains("58张")) {
//                    List<NewsMessage> items = new ArrayList<>();
//                    NewsMessage item = new NewsMessage();
//                    item.setTitle("照片墙");
//                    item.setDescription("整挺好");
//                    String url = "http://jinzhidata.com/resources/article/201908/02/09470697b838fb886a4046b03fbbe3dc99fa6b.jpg";
//                    item.setPicUrl(url);
//                    item.setUrl(url);
//                    items.add(item);
//                    respXml = WeChatMessageUtil.sendNewsMsg(requestMap, items);
                    respXml = WeChatMessageUtil.sendTextMsg(requestMap, "领取交通工程通用图58张，把《交通工程通用图58张》推送文章分享到您的朋友圈（勿屏蔽他人或仅自己可见），并将分享截图发给客服【客服微信号：ysmkefu】，客服会尽快发给您下载链接。【该内容为干货资源，良心内容，价值较高，谢谢大家理解】");
                } else if ("个人信息".equals(msg)) {
                    String accessToken = WeChatMessageUtil.getAccessToken();
                    JSONObject userInfo = WeChatMessageUtil.getUserInfo(accessToken, openid);
                    String nickname = userInfo.getString("nickname");
                    String city = userInfo.getString("city");
                    String province = userInfo.getString("province");
                    String country = userInfo.getString("country");
                    String headimgurl = userInfo.getString("headimgurl");
                    List<NewsMessage> items = new ArrayList<>();
                    NewsMessage item = new NewsMessage();
                    item.setTitle("你的信息");
                    item.setDescription("昵称:" + nickname + "  地址:" + country + " " + province + " " + city);
                    item.setPicUrl(headimgurl);
                    item.setUrl("http://jinzhidata.com");
                    items.add(item);
                    respXml = WeChatMessageUtil.sendNewsMsg(requestMap, items);
                }
            } else if (msgType.equals(Constant.REQ_MESSAGE_TYPE_EVENT)) {
                // 事件推送
                // 事件类型
                String eventType = requestMap.get(Constant.Event);
                if (eventType.equals(Constant.EVENT_TYPE_SUBSCRIBE)) {
                    // 关注
                    System.out.println("关注事件");
                    String eventKey = requestMap.get(Constant.Event_KEY);
                    if (eventKey != null) {
                        String accessToken = WeChatMessageUtil.getAccessToken();
                        JSONObject userInfo = WeChatMessageUtil.getUserInfo(accessToken, openid);
                        Map<String, String> map = JSONObject.parseObject(userInfo.toJSONString(), new TypeReference<Map<String, String>>() {
                        });
                        User user = userService.userLogin(map);
                        System.out.println(eventKey);
                        String sceneId = eventKey.substring(8);
                        System.out.println(sceneId);
                        String token = JwtUtil.sign(user.getUserId(), "WX");
                        sceneService.updateTokenBySceneId(sceneId, token);
                    }
                    respContent = "尽智研究院——交通行业招聘信息、项目合作、资源干货、前沿技术发布平台，旨在影响100万交通企业，促进交通行业大发展！";
                    respXml = WeChatMessageUtil.sendTextMsg(requestMap, respContent);
                } else if (eventType.equals(Constant.EVENT_TYPE_UNSUBSCRIBE)) {
                    // 取消关注
                    // TODO 取消订阅后用户不会再收到公众账号发送的消息，因此不需要回复
                } else if (eventType.equals(Constant.EVENT_TYPE_SCAN)) {
                    // 扫描带参数二维码
                    System.out.println("扫描带参数二维码");
                    String eventKey = requestMap.get(Constant.Event_KEY);
                    if (eventKey != null) {
                        String accessToken = WeChatMessageUtil.getAccessToken();
                        JSONObject userInfo = WeChatMessageUtil.getUserInfo(accessToken, openid);
                        Map<String, String> map = JSONObject.parseObject(userInfo.toJSONString(), new TypeReference<Map<String, String>>() {
                        });
                        User user = userService.userLogin(map);
                        String sceneId = eventKey;
                        System.out.println(sceneId);
                        String token = JwtUtil.sign(user.getUserId(), "WX");
                        sceneService.updateTokenBySceneId(sceneId, token);
                    }
                } else if (eventType.equals(Constant.EVENT_TYPE_CLICK)) {
                    String eventKey = requestMap.get(Constant.Event_KEY);
                    if ("ABOUT_US".equals(eventKey)) {
                        respXml = WeChatMessageUtil.sendTextMsg(requestMap, "尽智研究院——交通行业招聘信息、项目合作、资源干货、前沿技术发布平台，旨在影响100万交通企业，促进交通行业大发展！");
                    }
                }
            }
            if (respXml == null) {
                respXml = WeChatMessageUtil.sendTextMsg(requestMap, "您好，欢迎访问尽智研究院！");
            }
            return respXml;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


}
